# 请求客户端
import logging

import requests

from common.logger_util import logger


class ApiClient:
    def __init__(self, base_url):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({'Content-Type': 'application/json'})

    def request(
            self,
            method: str,
            path: str,
            headers: dict = None,
            params: dict = None,
            json: dict = None,
            retry: int = 3,
    ) -> requests.Response:
        """支持重试机制的请求方法"""
        url = self.base_url + path
        for attempt in range(retry):
            try:
                response = self.session.request(
                    method=method.upper(),
                    url=url,
                    params=params,
                    json=json,
                    headers=headers
                )
                self._log_request(response, attempt)
                response.raise_for_status()
                return response
            except requests.exceptions.RequestException as e:
                logger.error(f"API请求失败: {e}")
                if attempt == retry - 1:
                    raise RuntimeError(f"请求失败: {str(e)}") from e
                logger.warning(f"请求重试中... 第 {attempt + 1} 次")

    @staticmethod
    def _log_request(
            response: requests.Response,
            attempt: int
    ) -> None:
        """记录详细的请求日志"""
        log_data = {
            "method": response.request.method,
            "url": response.request.url,
            "headers": dict(response.request.headers),
            "body": response.request.body,
            "elapsed": response.elapsed.total_seconds(),
            "attempt": attempt + 1,
        }
        logger.info(f"request: {log_data}")
